package org.tloss.web.editor.database.editors;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.tloss.web.editor.Utils;
import org.tloss.web.editor.database.editors.jdbc.Column;
import org.tloss.web.editor.database.editors.jdbc.Table;
import org.tloss.web.editor.database.editors.service.DatabaseService;
import org.tloss.web.editor.model.Database;
import org.tloss.web.editor.utils.Constants;

public class TableListContentProvider implements ITreeContentProvider {

	@Override
	public void dispose() {

	}

	@Override
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {

	}

	@Override
	public Object[] getChildren(Object arg0) {

		return getElements(arg0);
	}

	@Override
	public Object[] getElements(Object arg0) {
		if (arg0 != null && arg0 instanceof Database) {
			Database database = (Database) arg0;
			if (database.getOffineModde()) {
				if (database.getTables() != null) {
					return database.getTables().toArray();
				}
				return Constants.EMPTY_ARRAY;
			}
			URL jarUrl;
			try {
				jarUrl = new URL("jar", "", "file:"
						+ new File(database.getJdbcLib()).getAbsolutePath()
						+ "!/");
				URLClassLoader classLoader = new URLClassLoader(
						new URL[] { jarUrl }, this.getClass().getClassLoader());

				DatabaseConnect connect = new DatabaseConnect(
						database.getJdbcURL(), database.getJdbcUsername(),
						database.getJdbcPassword(), database.getDriverClass(),
						classLoader);
				DatabaseService databaseService = new DatabaseService(connect);
				List<Table> tables = databaseService.getTables(database
						.getSchema().getCatalogName(), database.getSchema()
						.getSchemaName());
				if (tables == null || tables.isEmpty()) {
					if (database.getTables() != null) {
						return database.getTables().toArray();
					}
				} else {
					for (int i = 0; i < tables.size(); i++) {
						List<Column> columns = databaseService.getColumns(
								database.getSchema().getCatalogName(), database
										.getSchema().getSchemaName(), tables
										.get(i).getTableName());
						tables.get(i).setColumns(columns);
					}
					return tables.toArray();
				}
			} catch (MalformedURLException e) {
				Utils.logError("Config database is not correct", e);
			}

		}
		return Constants.EMPTY_ARRAY;
	}

	@Override
	public Object getParent(Object arg0) {
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element instanceof Database) {
			return true;
		}
		return false;
	}

}
